import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, Select, InputNumber, Upload, Button, Radio, Icon, message, TreeSelect } from 'antd';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import {  getBdToken, IsURL } from '@/utils/BdHelper';
import { ConfigListItem } from '../data';
import * as DataHelper from '@/helpers/DataHelper';
import TextArea from 'antd/lib/input/TextArea';

const FormItem = Form.Item;

export interface FormValueType extends Partial<ConfigListItem> {
  id?: number;
  name?: string;
  remark?: string;
  type?: string;
  nickame?: string;
  rank_num?: string;
}

interface ConfigFormProps extends FormComponentProps {
  modalVisible: boolean;
  otherValues: any;
  values: Partial<ConfigListItem>;
  onSubmit: (fieldsValue: FormValueType) => Promise<any>;
  onCancel: () => void;
  changeParamType: () => void;
  handleChangeType: (value:any) => void;
  handleSetPicture: (value:any) => void;
}

const ConfigForm: React.FC<ConfigFormProps> = props => {
  
  const [pictureModalVisible, setPictureModalVisible] = useState<boolean>(false);
  const [picturePreviewUrl, setPicturePreviewUrl] = useState<string>('');
  const { modalVisible, form, onSubmit: handleSubmit, onCancel, otherValues, values, handleChangeType,handleSetPicture } = props;
  const {isUpdate, radioType, picture, common} = otherValues;
  const token = getBdToken();

  const treeData = DataHelper.getTreeData(common)
  const treeProps = {
    treeData: treeData,
    // onChange: this.handleCategoryChange,
    treeDefaultExpandAll: true,
    searchPlaceholder: '搜索值',
    style: { width: '100%' },
  }

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // form.resetFields();
      if(isUpdate){
        fieldsValue.id = values.id;
      }
      
      // if(radioType == 'url' && !IsURL(fieldsValue.link_href)){
      //   message.error('请输入合法链接地址');
      //   return;
      // }
      
      if(picture.length > 0){
        if(picture[0].response && picture[0].response.code === 0){
          fieldsValue.file_url = picture[0].response.data.file_url;
        }else{
          fieldsValue.file_url = picture[0].url;
        }
      }
      handleSubmit(fieldsValue).then(success => {
        if(success){
          form.resetFields();
        }
      });
    });
  };

  const previewPicture = (file:any) =>{
    setPicturePreviewUrl(file.thumbUrl);
    setPictureModalVisible(true);
  }



  return (
    <Modal
      destroyOnClose
      title={isUpdate ? '编辑导航':"新增导航"}
      width='60%'
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
        <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label={formatMessage({id:'app.base.group'})}>
          {form.getFieldDecorator('config_group_id', {
            initialValue: isUpdate ? values.config_group_id?.toString() : otherValues.selectIndex,
            rules: [{required: true, message: formatMessage({id:'app.base.verify.group'})}],
          })(
            <Select
              showSearch
              placeholder={formatMessage({id:'app.base.choose'})}
              style={{width: '100%'}}
              disabled
            >
              {
                otherValues.common.sideBarList && 
                otherValues.common.sideBarList.map((d:any) => <Select.Option key={d.id} value={(d.id).toString()}>{d.name}</Select.Option>
                )
              }
            </Select>
          )}
        </FormItem>

        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="父级导航" help="默认为一级导航">
          {form.getFieldDecorator('parent_id', {
            initialValue: isUpdate ? values.parent_id : [],
            rules: [],
          })(<TreeSelect placeholder="请选择" {...treeProps} />)}
        </FormItem>

        <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label={'导航名称'}>
          {form.getFieldDecorator('name', {
            initialValue: isUpdate ? values.name : '',
            rules: [{required: true, message: '名称不能为空'}],
          })(<Input />)}
        </FormItem>

        <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label={'导航标识'}>
          {form.getFieldDecorator('nickname', {
            initialValue: isUpdate ? values.nickname : '',
            rules: [{required: true, message: formatMessage({id:'app.base.verify.variable-identification'})},{pattern: /^[A-Za-z0-9-_]+$/, message: formatMessage({id:'app.base.verify.error'})},],
          })(<Input placeholder={formatMessage({id:'app.base.placeholder.rules'})}/>)}
        </FormItem>


        <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}}  label={formatMessage({id:'app.base.variable-type'})}>
          {form.getFieldDecorator('link_type', {
            initialValue: isUpdate ? values.link_type : radioType,
            rules: [{required: true, message: '请输入链接地址'}],
          })(
            <Radio.Group  buttonStyle="solid" onChange={(e)=>handleChangeType(e.target.value)}>
              <Radio.Button key={'url'} value={'url'}>{'链接'}</Radio.Button>
              <Radio.Button key={'app'} value={'app'}>{'app内部'}</Radio.Button>
            </Radio.Group>
          )}
        </FormItem>

        <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label={'链接地址'}>
          {form.getFieldDecorator('link_href', {
            initialValue: isUpdate ? values.link_href : '',
            rules: [
              // {required: true, message: formatMessage({id:'app.base.verify.variable-title'})},
            ],
          })(<Input />)}
        </FormItem>

        <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label={formatMessage({id:'app.base.switch.file'})} help={common.tips && common.tips.picture_banner}>
          {form.getFieldDecorator('picture', {
            initialValue: isUpdate ? otherValues.picture : '',
            // rules: [{required: true, message: '请上传图片'}],
          })(
            <Upload
              {...{listType: 'picture',className: 'upload-list-inline',}}
              action="/api/admin/file/upload"
              defaultFileList={otherValues.picture}
              beforeUpload={(file) => {
                console.log('before upload file type:', file.type)
                // todo: 这里可以对上传文件类型做限制
                return true;
              }}
              data={{type: 'image'}}
              onRemove={() => handleSetPicture([])}
              onChange={(changeObj) => handleSetPicture(changeObj.fileList)}
              onPreview={previewPicture}
              headers={{
                Authorization: `Bearer ${token}`,
              }}
            >
              {
                picture.length === 0 ? (
                  <Button>
                    <Icon type="upload" /> {formatMessage({id:'app.base.upload'})}
                  </Button>
                ) : null
              }
            </Upload>
          )}
        </FormItem>

        <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label={'备注'}>
          {form.getFieldDecorator('remark', {
            initialValue: isUpdate ? values.remark : '',
            rules: [],
          })(<TextArea rows={2} disabled={false} placeholder="" />)}
        </FormItem>

        <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label={formatMessage({id:'app.base.sort'})}>
          {form.getFieldDecorator('rank_num', {
            initialValue: isUpdate ? values.rank_num : '',
            rules: [{required: true, message: formatMessage({id:'app.base.verify.sort'})}],
          })(<InputNumber style={{width: '100%'}} placeholder={formatMessage({id:'app.base.placeholder.sort'})} min={1} />)}
        </FormItem>

        <Modal
          title={formatMessage({id:'app.base.picture-preview'})}
          visible={pictureModalVisible}
          onOk={() => setPictureModalVisible(false)}
          onCancel={() => setPictureModalVisible(false)}
          afterClose={() => setPictureModalVisible(false)}
          footer={null}
        >
          <img src={picturePreviewUrl} width={'100%'}/>
        </Modal>
    </Modal>
  );
};

export default Form.create<ConfigFormProps>()(ConfigForm);
